package com.anxinr.controller;

import com.anxinr.pojo.entity.Users;
import com.anxinr.result.Result;
import com.anxinr.service.IUsersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author anxinr
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private IUsersService usersService ;

    @PostMapping("/login")
    public Result login(@RequestBody Users users) throws Exception {
        return new Result(usersService.login(users)) ;
    }

    @PostMapping("/query")
    public Result<IPage<Users>> query(@RequestBody Users users){
        return new Result(usersService.queryUsers(users)) ;
    }

    @PostMapping("/save")
    public Result save(@RequestBody Users users) throws Exception {
        try {
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(users.getName()), Users::getName, users.getName());
            Users one = usersService.getOne(wrapper);
            if (!Objects.isNull(one)){
                throw new Exception("用户名重复!");
            }
            return new Result(usersService.save(users)) ;
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
    }

    @PostMapping("/update")
    public Result update(@RequestBody Users users) throws Exception {
        try {
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(users.getName()), Users::getName, users.getName());
            Users one = usersService.getOne(wrapper);
            if (!Objects.isNull(one)){
                throw new Exception("用户名重复!");
            }
            return new Result(usersService.updateById(users)) ;
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
    }

    @GetMapping("/remove")
    public Result remove(@RequestParam("name") String name){
        try {
            LambdaUpdateWrapper<Users> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Users::getName,name);
            usersService.remove(wrapper);
            return Result.success() ;
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
    }


}
